package com.cx.common.winxin;

import com.cx.common.utils.DateUtils;
import com.cx.common.utils.JsonUtils;
import com.cx.common.http.HttpsClient;
import com.cx.common.thread.ExecutorUtils;
import com.cx.common.winxin.model.TokenVO;
import com.cx.common.winxin.model.WinxinNoticeVO;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 微信工具
 * 
 * @Author:cxy
 * @Date:2019/10/24 15:11
 * 
 */
public class WinxinUtils {

	private static Logger _log = LoggerFactory.getLogger(WinxinUtils.class);

	/** 企业应用号 */
	private static String corpid = "";

	/** 企业应用号密匙 */
	private static String corpsecret = "";

	/** 获取token的Url */
	private static String tokenUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpid + "&corpsecret="
			+ corpsecret;

	/** 发送消息的Url */
	private static String sendMessageUrl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=";

	/** 有效时间 */
	private static volatile TokenVO tokenVO = null;

	public static void asyncSendMessage(String message) {
		ExecutorUtils.submit(new Runnable() {
			public void run() {
				sendMessage(message);
			}
		});
	}

	/**
	 * 发送报警
	 * 
	 * @param message
	 */
	public static void sendMessage(String message) {
		if (!isTokenValid()) {
			initToken();
		}
		String url = sendMessageUrl + tokenVO.getAccess_token();
		WinxinNoticeVO winxinNoticeVO = WinxinNoticeVO.valueOf();
		winxinNoticeVO.sendText(message);
		String notice = JsonUtils.object2String(winxinNoticeVO);
		HttpsClient.httpsPost(url, notice);
	}

	/**
	 * 获取token
	 */
	public static synchronized void initToken() {
		if (isTokenValid()) {
			return;
		}
		String tokenInfo = HttpsClient.httpsGet(tokenUrl);
		if (StringUtils.isBlank(tokenInfo)) {
			return;
		}
		TokenVO curTokenVO = JsonUtils.string2Object(tokenInfo, TokenVO.class);
		int errcode = curTokenVO.getErrcode();
		if (errcode != 0) {
			_log.error("get token errcode:[{}]", errcode);
			return;
		}
		curTokenVO.setExpireSecond(DateUtils.getCurrentSecond() + curTokenVO.getExpires_in());
		tokenVO = curTokenVO;
	}

	/**
	 * token是否有效
	 * 
	 * @return
	 */
	private static boolean isTokenValid() {
		if (tokenVO == null) {
			return false;
		}
		int currentSecond = DateUtils.getCurrentSecond();
		if (currentSecond > tokenVO.getExpireSecond()) {
			return false;
		}
		return true;
	}

}
